﻿using System;
using System.Configuration;
using System.Windows.Forms;

namespace AD域工具.Tool
{

    #region 程序配置类
    /// <summary>
    /// 程序配置类
    /// </summary>
    #endregion
    public class AppConfig
    {
        #region 修改配置
        /// <summary>
        /// 修改配置
        /// </summary>
        /// <param name="key">修改的项</param>
        /// <param name="value">修改的值</param>
        #endregion
        public static bool SetValue(string key, string value)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                if (config.AppSettings.Settings[key] != null)
                {
                    config.AppSettings.Settings[key].Value = value;
                }
                else
                {
                    config.AppSettings.Settings.Add(key, value);
                }
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
                return true;
            }
            catch
            {
                return false;
            }
        }

        #region 读取配置
        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="key">读取的项</param>
        /// <returns>读取的值</returns>
        #endregion
        public static string GetValue(string key)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
            {
                return config.AppSettings.Settings[key].Value;
            }
            else
            {
                return null;
            }
        }

        #region 绑定输入框与程序配置
        /// <summary>
        /// 绑定输入框与程序配置
        /// </summary>
        /// <param name="textBox">绑定的输入框</param>
        /// <param name="key">绑定的配置项</param>
        #endregion
        public static void BindInput(TextBox textBox, string key) {
            textBox.Text = AppConfig.GetValue(key);
            textBox.TextChanged += (object sender, EventArgs e) =>
            {
                AppConfig.SetValue(key, textBox.Text);
            };
        }
    }
}
